<?php
/**
 * 轻舟CMS(QZLOG)
 *
 * 一款基于PHP+MYSQL的开源内容管理系统，模板标签简单、可扩展性强，利于二次开发，轻松建站的首选利器。
 *
 * @package     QZLOG
 * @license     http://www.qzlog.com/license
 * @link        http://www.qzlog.com
 * @mail        info@shyohan.com
 * @since       Version 3.0
 * @copyright   Copyright (c) 2015 - 2017 上海优翰信息科技有限公司. All rights reserved.
 */

defined('IN_QZLOG') OR exit('QZLOG:No direct script access allowed!');

/**
 * 权限组别管理
 * @author LINK <link@shyohan.com>
 */
class AuthController extends QzController
{
    private $db;

    public function __init()
    {
        $this->db = K("AuthGroup");
    }

    /**
     * 主页
     * @author LINK <link@shyohan.com>
     */
    public function index()
    {
        $count = $this->db->count();
        $page = new Page($count);
        $this->page = $page->show();
        $data = $this->db->order("id DESC")->limit($page->limit())->all();
        int_to_string($data, array('status' => array(1 => '正常', 0 => '禁用')));
        $bread = make_bread(array('权限管理' => '', '用户组列表' => ''));
        $this->assign('data', $data);
        $this->assign('bread', $bread);
        $this->display();
    }

    /**
     * 添加
     * @author LINK <link@shyohan.com>
     */
    public function add()
    {
        if (IS_POST) {
            if ($this->db->addGroup()) {
                qz_ajax_return("新增成功!");
            } else {
                qz_ajax_return_error($this->db->error);
            }
        } else {
            $this->display();
        }
    }

    /**
     * 编辑
     * @author LINK <link@shyohan.com>
     */
    public function edit()
    {
        if (IS_POST) {
            if ($this->db->editGroup()) {
                qz_ajax_return("编辑成功!");
            } else {
                qz_ajax_return_error($this->db->error);
            }
        } else {
            $id = Q('id');
            $qz = $this->db->find($id);
            $this->assign('qz', $qz);
            $this->display();
        }
    }

    /**
     * 删除 & 批量删除
     * @author LINK <link@shyohan.com>
     */
    public function del()
    {
        if ($this->db->delGroup()) {
            qz_ajax_return("删除成功!");
        } else {
            qz_ajax_return_error($this->db->error);
        }
    }

    /**
     * 状态修改
     * @author LINK <link@shyohan.com>
     */
    public function changeStatus()
    {
        if ($this->db->changeStatusGroup()) {
            qz_ajax_return("操作成功!");
        } else {
            qz_ajax_return_error($this->db->error);
        }
    }

    /**
     * 访问授权页面
     * @author LINK <link@shyohan.com>
     */
    public function access()
    {
        $this->updateRules();
        $id = Q('group_id');
        if (!$id) {
            qz_ajax_return_error('参数错误!');
        }
        $this_group = $this->db->find($id);
        $node_list = $this->returnNodes();
        $main_rules = M('auth_rule')->field('id,name')->where(array('status' => 1, 'type' => 2))->order('id DESC')->all();
        $child_rules = M('auth_rule')->field('id,name')->where(array('status' => 1, 'type' => 1))->order('id DESC')->all();
        $main_rules = $this->array_row_format($main_rules);
        $child_rules = $this->array_row_format($child_rules);
        $this->assign('this_group', $this_group);
        $this->assign('node_list', $node_list);
        $this->assign('main_rules', $main_rules);
        $this->assign('child_rules', $child_rules);
        $this->display();
    }

    /**
     * 节点二维数组格式化为 url=>id 格式
     * @author LINK <link@shyohan.com>
     * @param $array
     * @return array
     */
    public function array_row_format($array)
    {
        $data = array();
        foreach ($array as $val) {
            $data[$val['name']] = $val['id'];
        }
        return $data;
    }

    /**
     * 用户组数据写入/更新
     * @author LINK <link@shyohan.com>
     */
    public function writeGroup()
    {
        if ($this->db->writeGroup()) {
            qz_ajax_return("操作成功!");
        } else {
            qz_ajax_return_error($this->db->error);
        }
    }

    /**
     * 用户组授权用户列表
     * @author LINK <link@shyohan.com>
     */
    public function user()
    {
        $group_id = Q('group_id');
        if (!$group_id) {
            qz_ajax_return_error('参数错误!');
        }
        $this_group = $this->db->find($group_id);
        $count = $this->db->count();
        $page = new Page($count);
        $this->page = $page->show();
        $data = M()->field('id,username,nickname,last_login_time,last_login_ip,status')
            ->join('__member__ u JOIN __auth_group_access__ r ON u.id=r.uid')
            ->where(array('r.group_id' => $group_id))
            ->order("id DESC")->limit($page->limit())->all();
        if ($data) {
            foreach ($data as &$key) {
                $key['last_login_time'] = date('Y-m-d h:i:s', $key['last_login_time']);
            }
        }
        int_to_string($data, array('status' => array(1 => '正常', 0 => '禁用')));
        $this->assign('this_group', $this_group);
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 新增用户授权
     * @author LINK <link@shyohan.com>
     */
    public function addToGroup()
    {
        if (IS_POST) {
            if ($this->db->addUserToGroup()) {
                qz_ajax_return("新增成功!");
            } else {
                qz_ajax_return_error($this->db->error);
            }
        } else {
            $this->display();
        }
    }

    /**
     * 解除用户授权
     * @author LINK <link@shyohan.com>
     */
    public function removeFromGroup()
    {
        $uid = Q('id');
        $gid = Q('group_id');
//        if ($uid == UID) {
//            qz_ajax_return_error('不允许解除自身授权');
//        }
        if (empty($uid) || empty($gid)) {
            qz_ajax_return_error('参数有误');
        }
        if (!$this->db->find($gid)) {
            qz_ajax_return_error('用户组不存在');
        }
        if (M('auth_group_access')->where(array('uid' => $uid, 'group_id' => $gid))->delete()) {
            qz_ajax_return("操作成功!");
        } else {
            qz_ajax_return_error('操作失败');
        }
    }

    /**
     * 后台节点配置的url作为规则存入auth_rule
     * 执行新节点的插入,已有节点的更新,无效规则的删除三项任务
     * @author LINK <link@shyohan.com>
     */
    public function updateRules()
    {
        //需要新增的节点必然位于$nodes
        $nodes = $this->returnNodes(false);
        //需要更新和删除的节点必然位于$rules
        $rules = M('auth_rule')->order("name ASC")->all();
        //构建insert数据
        $data = array();//保存需要插入和更新的新节点
        foreach ($nodes as $value) {
            $temp['name'] = $value['url'];
            $temp['title'] = $value['title'];
            if ($value['pid'] > 0) {
                $temp['type'] = 1;
            } else {
                $temp['type'] = 2;
            }
            $temp['status'] = 1;
            $data[strtolower($temp['name'] . $temp['type'])] = $temp;//去除重复项
        }
        $update = array();//保存需要更新的节点
        $ids = array();//保存需要删除的节点的id
        foreach ($rules as $index => $rule) {
            $key = strtolower($rule['name'] . $rule['type']);
            if (isset($data[$key])) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']] = $rule;
            } elseif ($rule['status'] == 1) {
                $ids[] = $rule['id'];
            }
        }
        if (count($update)) {
            foreach ($update as $k => $row) {
                if ($row != $diff[$row['id']]) {
                    M('auth_rule')->save($row);
                }
            }
        }
        if (count($ids)) {
            $map['id'] = array('in', $ids);
            M('auth_rule')->where($map)->del();
            //删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if (count($data)) {
            foreach ($data as $value) {
                M('auth_rule')->add($value);
            }
        }
        if ($this->db->error) {
            return false;
        } else {
            return true;
        }
    }
}
